package com.zjbd.shuaiyangauth.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zjbd.shuaiyangcommoncore.entity.DyUsers;
import com.zjbd.shuaiyangcommoncore.result.Result;
import com.zjbd.shuaiyangcommoncore.service.DyUsersService;

import com.zjbd.shuaiyangcommoncore.vo.DyUsersNamePassVo;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Tag(name = "登录相关")
@Slf4j
@RestController
@RequestMapping("/shuaiyang/auth/login")
public class UserLoginController {

    @Autowired
    private DyUsersService dyUsersService;

    @PostMapping("/namePassLogin")
    public Result namePassLogin(@Valid @RequestBody DyUsersNamePassVo dyUsersNamePassVo){
    //通过用户名查询这个用户
    String username = dyUsersNamePassVo.getUsername();
    log.info("用户名{}",username);
    QueryWrapper<DyUsers> queryWrapper = new QueryWrapper<DyUsers>()
            .eq("username", username);
    DyUsers one = dyUsersService.getOne(queryWrapper);
    //如果不存在
    if (one == null){
        return Result.error("用户名或密码错误");
    }
    String password = dyUsersNamePassVo.getPassword();
    log.info("密码{}",password);

    //对密码就行加密
    Digester md5 = new Digester(DigestAlgorithm.MD5);
    //加密
    String md5Pass = md5.digestHex(password + one.getSalt());
    log.info("密码加密成功{}",md5Pass);
    if (!one.getPassword().equals(md5Pass)){
        return Result.error("用户名或密码错误");
    }
    //通过sa-token，记录登录
    StpUtil.login(one.getId());
    //获取到id加密后的token
    String token = StpUtil.getTokenInfo().getTokenValue();
    return Result.success(token);
}

}
